<template>
  <section>
    <el-row v-if="!next" v-loading="loading">
      <el-row style="padding-bottom: 10px">
        <el-col :span="4">选择用户：</el-col>
        <el-col :span="20">
          <el-select v-model="selUser" multiple :filterable="true" remote :reserve-keyword="false" default-first-option  placeholder="请输入姓名"
                     :remote-method="remoteMethod" :loading="loading" size="mini">
            <el-option v-for="user in users" :key="user.id" :label="user.name" :value="user.id">
              <span style="float: left">{{ user.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ user.phone }}</span>
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row type="flex" style="border-top:1px solid #d9d9d9;padding:10px 0;" align="middle" v-for="(sku,index) in uiSkus" :key="index">
        <el-col :span="4">{{sku.label}}：</el-col>
        <el-col :span="20">
          <el-button :type="sku.selVal === prop.text? 'primary':''"
                     v-for="(prop,index2) in sku.props" size="small" :disabled="!prop.isAble" @click="propClick(sku,prop)" :key="index2">
            {{prop.text}}？？？
          </el-button>
        </el-col>
      </el-row>
      <el-row >
        <el-col :span="22" style="text-align: right;line-height: 20px">余量：</el-col>
        <el-col :span="2" style="text-align: left;line-height: 20px">{{virtualStock}}</el-col>
      </el-row>
      <el-row style="height:64px;line-height:64px;">
        <el-col :span="8">&nbsp;</el-col>
        <el-col :span="8"><el-button type="primary" :disabled="!registerAble" size="small" @click="btnRegister">挂号</el-button></el-col>
        <el-col :span="8"><el-button size="small" @click="btnCancel">取消</el-button></el-col>
      </el-row>
    </el-row>
    <el-row >
      <Showpay v-if="next" :orders="checkOrders" :pay="currPay" v-on:cancel="cancel"></Showpay>
    </el-row>
  </section>
</template>

<script>
  import Showpay from "./showPay";
  import { mapActions} from 'vuex'
  import test from './allOrder'
  export default {
    name: "showgoods",
    props: ['goods'],
    components: {Showpay},
    data(){
      return {
        next:false,
        registerAble:false,
        uiSkus:[],
        stockList:[],
        users:[],
        selUser:null,
        loading: false,
        currOrderDetial:null,
        virtualStock:0,
        checkOrders:[],
        currPay:{}
      }
    },
    mounted(){
      //console.log(this.goods)
      this.createUISku()
    },
    created(){
      this.getStockList()
    },
    watch:{
      goods(){
        this.createUISku()
      },
      selUser(nv,ov){
        console.log(nv)
      }
    },
    methods:{
      ...mapActions({
        fetch: 'fetch'
      }),
      cancel(){
        this.$emit('cancel')
      },
      remoteMethod(query) {
        const req = {
          keyword: query
        }
        this.fetch({name:"getUserList",data:{...req}})
          .then(res=>{
            console.log(res)
            this.users=res
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      getStockList(){
        this.fetch({name:"getStockList"})
          .then(res=>{
            console.log(res)
            this.stockList=res
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      btnCancel(){
        console.log('--------------')
        this.$emit('cancel')
      },
      checkinUser(){
        console.log(this.selUser)
      },
      btnRegister(){
        this.loading = true
        // //判断该用户该sku是否重复
        if(!this.selUser || this.selUser.length<=0){
          this.$message({type:'error',message:'未选择用户'})
          return
        }
        if((this.virtualStock - this.selUser.length ) < 0 ){
          this.$message({type:'error',message:'库存不足'})
          return
        }
        //做事情,单个订单
        let params = this.createParams()
        params.userId = this.selUser[0]
        this.createOrder(params)
        // for(let i=0;i<this.selUser.length;i++){
        //   let params = this.createParams()
        //   //结合所选项目，批量生成挂号订单
        //   params.userId = this.selUser[i]
        //   this.createOrder(params)
        // }
      },
      /*
        创建参数 对象
       */
      createParams(){
        let o = {
          title:this.currOrderDetial.props,
          price:this.currOrderDetial.price,
          totalPrice:this.currOrderDetial.price,
          num:1,
          sn:this.currOrderDetial.sn
        }
        o.data={
          ...this.currOrderDetial.skuDetail,
          goodsTypeCode:this.goods.goodsType.code,
        }
        let orderItems =[]
        orderItems.push(o)
        return {
          title:this.goods.name,
          departmentId:this.goods.departmentId,
          orderItems:JSON.stringify(orderItems)
        }
      },
      createOrder(params){
        console.log(params)
        this.fetch({name:"createOrderByManager",data:params})
          .then(res=>{
            console.log(res)
            this.checkOrders.push(res)
            this.currPay = res
            this.loading = false
            this.$confirm('订单创建成功, 是否进入支付?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              //进入支付界面
              this.next = true
            }).catch(() => {
              this.$emit('cancel')
            })
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      createUISku(){
        this.uiSkus=[]
        console.log(this.goods)
        this.goods.goodsSkus.forEach(gs=>{
          let tmpProps= gs.props.split(';')
          if(tmpProps.length>0){
            tmpProps.forEach(tp=>{
              let tmpProp = tp.split(':')
              if(tmpProp.length === 2){
                let sku = this.uiSkus.find(us=>us.label === tmpProp[0])
                if(!sku){
                  sku = {label:tmpProp[0],selVal:null,props:[]}
                  this.uiSkus.push(sku)
                }
                let pIndex =  sku.props.findIndex(s=>s.text === tmpProp[1])
                if(!(pIndex >= 0))
                  sku.props.push({text:tmpProp[1],isAble:true})
              }
            })
          }
        })
        console.log(this.uiSkus)
      },
      valChange(sku){
        this.virtualStock =0
        console.log(sku)
        //收集选中状态 的值
        let params = []
        this.uiSkus.forEach(us=>{
          if(us.selVal)
            params.push({key:us.label,val:us.selVal})
        })
        /*
          检查所有原始规格数据
          日期:2018-06-02;时间:下午;科室:儿童;医生:王梦倩
          [
            {key:'日期',val:'2018-06-02'},
            {key:'时间',val:'下午'},
            {key:'科室',val:'儿童'},
          ]
        */
        let founds = []
        this.goods.goodsSkus.forEach(gs=>{
          if(this.checkIn(params,gs.props))
            founds.push(gs)
        })
        if(params.length === this.uiSkus.length){
          this.currOrderDetial = founds[0]
          this.registerAble = true//挂号按钮可用
          let skuDetail={}
          for(let i=0;i<params.length;i++){
            let tmp = params[i]
            skuDetail[tmp.key]=tmp.val
          }
          this.currOrderDetial.skuDetail = skuDetail
          if(founds[0].sn){
            let stock = this.stockList.find(s => s.sn == founds[0].sn)
            console.log(this.stockList)
            this.virtualStock +=stock.virtualStock
          }
        }else {
          this.registerAble = false
          this.virtualStock =0
        }
        //找到了能匹配现在选项 的所有 sku
        console.log(founds)
        //设置未选中状态 的 prop 是否可用
        this.updateUISku(founds,sku)
      },
      checkIn(params,props){//检查选项匹配
        for(let i=0;i<params.length;i++){
          let p = params[i]
          let f = p.key+':'+p.val
          let index = props.indexOf(f)
          if(!(index>=0)) return false
        }
        return true
      },
      updateUISku(skus,currSku){
        //先禁用所有属性？？？
        this.uiSkus.forEach(us=>{
          if(us.label !== currSku.label)
            us.props.forEach(p=>{
              p.isAble=false
            })
        })
        skus.forEach(gs=>{
          let tmpProps= gs.props.split(';')
          if(tmpProps.length>0){
            tmpProps.forEach(tp=>{
              let tmpProp = tp.split(':')
              if(tmpProp.length === 2){
                let sku = this.uiSkus.find(us=>us.label === tmpProp[0])
                if(sku){
                  let p =  sku.props.find(s=>s.text === tmpProp[1])
                  p.isAble=true
                }
              }
            })
          }
        })
      },
      propClick(sku,prop){
        if(sku.selVal && sku.selVal === prop.text)
          sku.selVal = null
        else
          sku.selVal = prop.text
        this.valChange(sku)
      }
    }
  }
</script>

<style scoped>

</style>
